package com.cheli.managerAsset.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cheli.managerAsset.entity.AsCategory;
import com.cheli.managerAsset.entity.excel.CategoryData;
import com.cheli.managerAsset.service.AsCategoryService;
import com.cheli.servicebase.config.exceptionhandler.MyException;

/**
 * @Classname CatagoryExcelListener
 * @Description 资产类别监听器
 * @Date 2021/3/28 15:24
 * @Created by cl
 */
public class CategoryExcelListener extends AnalysisEventListener<CategoryData> {

    public AsCategoryService categoryService;
    public CategoryExcelListener(){}

    public CategoryExcelListener(AsCategoryService categoryService){
        this.categoryService = categoryService;
    }

    @Override
    public void invoke(CategoryData categoryData, AnalysisContext analysisContext) {
        if(categoryData == null){
            throw new MyException(20001, "文件数据为空");
        }
       AsCategory existOneCategory = existOneCategory(categoryData.getOneCatagoryName());
        if(existOneCategory == null){
            existOneCategory = new AsCategory();
            existOneCategory.setParentId("0");
            existOneCategory.setTitle(categoryData.getOneCatagoryName());
            categoryService.save(existOneCategory);
        }

        String pid = existOneCategory.getId();
       //判断二级分类是否重复
        AsCategory existTwoCategory = existTwoCategory(categoryData.getTwoCatagoryName(), pid);
        if(existTwoCategory == null){
            existTwoCategory = new AsCategory();
            existTwoCategory.setParentId(pid);
            existTwoCategory.setTitle(categoryData.getTwoCatagoryName());
            categoryService.save(existTwoCategory);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

   private AsCategory existOneCategory(String name){
        QueryWrapper<AsCategory> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id","0");
        return categoryService.getOne(wrapper);
    }

   private AsCategory existTwoCategory(String name, String pid){
        QueryWrapper<AsCategory> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id",pid);
        return categoryService.getOne(wrapper);
    }

}
